package com.lh.glorypavilion.service.aliyunoss.controller.admin;

import com.lh.glorypavilion.exception.glorypavilionEx;
import com.lh.glorypavilion.result.R;
import com.lh.glorypavilion.result.ResultCode;
import com.lh.glorypavilion.service.aliyunoss.service.FileService;
import com.lh.glorypavilion.util.ExceptionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

//@CrossOrigin
@Api(description = "阿里云oss上传")
@RestController
@RequestMapping("/admin/oss/file")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(@ApiParam(value = "文件",required = true) @RequestParam("file") MultipartFile file,
                    @ApiParam(value = "文件夹名称",required = true) @RequestParam("module") String module) {
        String uploadUrl = null;
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            uploadUrl = fileService.upload(inputStream, module, originalFilename);
        } catch (Exception e) {
            log.info(ExceptionUtils.getMessage(e));
            throw new glorypavilionEx(ResultCode.FILE_UPLOAD_ERROR);
        }

        return R.ok().message("文件上传成功").data("url",uploadUrl);
    }

    @ApiOperation("文件删除")
    @DeleteMapping("remove")
    public R delete(@ApiParam("文件路径名称") @RequestParam("url") String url){
        fileService.remove(url);
        return R.ok().message("文件删除成功");
    }


}
